package com.framework.bdf4j.socket.coder;

import java.util.List;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

public class PackageFrameDecoder extends ByteToMessageDecoder 
{
    @Override
    protected void decode(ChannelHandlerContext arg0, ByteBuf arg1, List<Object> arg2) throws Exception 
    {
        int len = arg1.readableBytes();
        if(len <= 3){
            return;
        }
        arg1.markReaderIndex();
        int headerOffset = indexOf(arg1);
        if(headerOffset < 0){
            return;
        }

        if(arg1.readableBytes() < 2){
            arg1.resetReaderIndex();
            return;
        }

        int datalength = arg1.getShort(headerOffset+1);
        if(datalength < 0)
        {
            arg1.resetReaderIndex();
            return;
        }

        int readablelen = arg1.readableBytes();
        if(readablelen < 3 + datalength + 1)
        {
            arg1.resetReaderIndex();
            return;
        }

        ByteBuf frame = arg0.alloc().buffer(3 + datalength + 1);
        arg1.readBytes(frame);
        arg2.add(frame);
        arg1.discardReadBytes();
    }

    private int indexOf(ByteBuf haystack) {
        for (int i = haystack.readerIndex(); i < haystack.writerIndex(); i++) {
            int haystackIndex = i;
            if(haystack.getByte(haystackIndex) == 0x7E)
            {
                return i;
            }
        }
        return -1;
    }

}


